<?php
	// Fonctions utiles à ce projet
    
    function data($data, $ligne, $champ)
	{
		return $data[$ligne][$champ];
	}
	
	function nbres($data)
	{
		return count($data);
	}
    
    function now()
    {
        return date('Y-m-d H:i:s');
    }
    
    function idAlpha($size = 9, $table = '', $idName = '')
    {
        $newId = strtoupper(makePassword($size));
        if (strlen($table) && strlen($idName)) {
            $db = db();
            $q = "SELECT COUNT($idName) AS nb FROM $table WHERE $idName = '" . sanitsql($newId) . "'";
            $res = $db->fetchArray_one($q);
            if (count($res)) {
                if ($res['nb'] > 0) {
                    return idAlpha($size, $table, $idName);
                } else {
                    return $newId;
                }
            }
        } else {
            return $newId;
        }
    }
    
    function getIP()
    {
		$rem = @$_SERVER["REMOTE_ADDR"];
		$ff  = @$_SERVER["HTTP_X_FORWARDED_FOR"];
		$ci  = @$_SERVER["HTTP_CLIENT_IP"];
		if(preg_match('/^(?:192\.168|172\.16|10\.|127\.)/', $rem)) { 
			if($ff) { return $ff; }
			if($ci) { return $ci; }
			return $rem;
		} else {
			if($rem) { return $rem; }
			if($ff) { return $ff; }
			if($ci) { return $ci; }
			return "UNKNOWN";
		}
	}
    
    function antiFlood()
    {
        $uri = $_SERVER['REQUEST_URI'];
        $ip = getIP();
        setvar('__IP__', $ip);
        $date = date('d/m/Y H:i');
        $maxSamePagePerMinute = config('app.maxSamePagePerMinute');
        $md5 = md5($uri . $ip . $date);
        if (!$_SESSION['antiFlood']) {
            $_SESSION['antiFlood'] = array();
        }
        if (!$_SESSION['antiFlood'][$md5]) {
            $_SESSION['antiFlood'][$md5] = 1;
        }
        
        if ($_SESSION['antiFlood'][$md5] > $maxSamePagePerMinute) {
            die('flooding');
        } else {
            $_SESSION['antiFlood'][$md5]++;
        }
    }
    
    function sourceWZ($file, $line_number, $padding = 5)
	{
		if (!$file || !is_readable($file)) {
			// Continuing will cause errors
			return false;
		}

		// Open the file and set the line position
		$file = fopen($file, 'r');
		$line = 0;

		// Set the reading range
		$range = array('start' => $line_number - $padding, 'end' => $line_number + $padding);

		// Set the zero-padding amount for line numbers
		$format = '% ' . strlen($range['end']) . 'd';

		$source = '';
		while (($row = fgets($file)) !== false) {
			// Increment the line number
			if (++$line > $range['end'])
				break;

			if ($line >= $range['start']) {
				// Make the row safe for output
				$row = htmlspecialchars($row, ENT_NOQUOTES, config('app.charset'));

				// Trim whitespace and sanitize the row
				$row = '<span class="number">' . sprintf($format, $line) . '</span> ' . $row;

				if ($line === $line_number) {
					// Apply highlighting to this row
					$row = '<span class="line highlight">' . $row . '</span>';
				} else {
					$row = '<span class="line">' . $row . '</span>';
				}

				// Add to the captured source
				$source .= $row;
			}
		}

		// Close the file
		fclose($file);

		return '<pre class="source"><code>' . $source . '</code></pre>';
	}
    
    function traceWZ(array $trace = null)
	{
		if ($trace === null) {
			// Start a new trace
			$trace = debug_backtrace();
		}

		// Non-standard function calls
		$statements = array('include', 'include_once', 'require', 'require_once');

		$output = array();
		foreach ($trace as $step) {
			if ( ! isset($step['function'])) {
				// Invalid trace step
				continue;
			}

			if (isset($step['file']) && isset($step['line'])) {
				// Include the source of this step
				$source = sourceWZ($step['file'], $step['line']);
			}

			if (isset($step['file'])) {
				$file = $step['file'];

				if (isset($step['line'])) {
					$line = $step['line'];
				}
			}

			// function()
			$function = $step['function'];

			if (in_array($step['function'], $statements)) {
				if (empty($step['args'])) {
					// No arguments
					$args = array();
				} else {
					// Sanitize the file path
					$args = array($step['args'][0]);
				}
			} elseif (isset($step['args'])) {
				if ( ! function_exists($step['function']) || strpos($step['function'], '{closure}') !== false) {
					// Introspection on closures or language constructs in a stack trace is impossible
					$params = null;
				} else {
					if (isset($step['class'])) {
						if (method_exists($step['class'], $step['function'])) {
							$reflection = new ReflectionMethod($step['class'], $step['function']);
						} else {
							$reflection = new ReflectionMethod($step['class'], '__call');
						}
					} else {
						$reflection = new ReflectionFunction($step['function']);
					}

					// Get the function parameters
					$params = $reflection->getParameters();
				}

				$args = array();

				foreach ($step['args'] as $i => $arg) {
					if (isset($params[$i])) {
						// Assign the argument by the parameter name
						$args[$params[$i]->name] = $arg;
					} else {
						// Assign the argument by number
						$args[$i] = $arg;
					}
				}
			}

			if (isset($step['class'])) {
				// Class->method() or Class::method()
				$function = $step['class'] . $step['type'] . $step['function'];
			}

			$output[] = array(
				'function' => $function,
				'args'     => isset($args)   ? $args : null,
				'file'     => isset($file)   ? $file : null,
				'line'     => isset($line)   ? $line : null,
				'source'   => isset($source) ? $source : null
			);

			unset($function, $args, $file, $line, $source);
		}

		return $output;
	}
    
    set_exception_handler('exceptionHandler');
    function exceptionHandler(Exception $exception) 
    {
        // these are our templates
        $traceline = "#%s %s(%s): %s(%s)";
        $msg = "PHP Fatal error:  Uncaught exception '%s' with message '%s' in %s:%s\nStack trace:\n%s\n  thrown in %s on line %s";

        // alter your trace as you please, here
        $trace = $exception->getTrace();
        foreach ($trace as $key => $stackPoint) {
            // I'm converting arguments to their type
            // (prevents passwords from ever getting logged as anything other than 'string')
            $trace[$key]['args'] = array_map('gettype', $trace[$key]['args']);
        }

        // build your tracelines
        $result = array();
        foreach ($trace as $key => $stackPoint) {
            $result[] = sprintf(
                $traceline,
                $key,
                $stackPoint['file'],
                $stackPoint['line'],
                $stackPoint['function'],
                implode(', ', $stackPoint['args'])
            );
        }
        // trace always ends with {main}
        $result[] = '#' . ++$key . ' {main}';

        // write tracelines into main template
        $msg = sprintf(
            $msg,
            get_class($exception),
            $exception->getMessage(),
            $exception->getFile(),
            $exception->getLine(),
            implode("\n", $result),
            $exception->getFile(),
            $exception->getLine()
        );

        echo($msg);
    }
    
    set_error_handler("myErrorHandler");
    function myErrorHandler($errno, $errstr, $errfile, $errline)
    {
        $trace = traceWZ();
        switch ($errno) {
            case E_USER_ERROR:
                if ($errstr == "(SQL)"){
                    // handling an sql error
                    echo "<b>SQL Error</b> [$errno] " . SQLMESSAGE . "<br />\n";
                    echo "Query : " . SQLQUERY . "<br />\n";
                    echo "On line " . SQLERRORLINE . " in file " . SQLERRORFILE . " ";
                    echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
                    echo "Aborting...<br />\n";
                } else {
                    echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
                    echo "  Fatal error on line $errline in file $errfile";
                    echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
                    echo "Aborting...<br />\n";
                }
                echo '<hr />' . $trace . '<hr />';
                exit(1);
                break;

            case E_USER_WARNING:
            case E_USER_NOTICE:
        }
        /* Don't execute PHP internal error handler */
        return true;
    }
    
    function getPreferredLanguage()
    {
        if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && ($n = preg_match_all('/([\w\-]+)\s*(;\s*q\s*=\s*(\d*\.\d*))?/', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches)) > 0) {
            $languages = array();
            for($i = 0 ; $i < $n ; $i++) {
                $languages[$matches[1][$i]] = empty($matches[3][$i]) ? 1.0 : floatval($matches[3][$i]);
            }
            arsort($languages);
            foreach($languages as $language => $pref) {
                return strtolower(_r('-', '_', $language));
            }
        }
        return false;
    }
    
    function ga()
    {
        $gaAccount = config('ga.account');
        $gaHost = config('ga.host');
        $js = '<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(["_setAccount", "' . $gaAccount . '"]);
  _gaq.push(["_setDomainName", "' . $gaHost . '"]);
  _gaq.push(["_trackPageview"]);

  (function() {
    var ga = document.createElement("script"); 
    ga.type = "text/javascript"; 
    ga.async = true;
    ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";
    var s = document.getElementsByTagName("script")[0]; 
    s.parentNode.insertBefore(ga, s);
  })();
  </script>';
        return $js;
    }
    
    function gFont($font)
    {
        $js = "<script type=\"text/javascript\">
          WebFontConfig = { 
            google: { families: [ '$font' ] } 
          };  
          (function() {
            var wf = document.createElement('script');
            wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
                '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
            wf.type = 'text/javascript';
            wf.async = 'true';
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(wf, s); 
          })();
        </script>";
        return $js;
    }
    
    function addJs($src, $echo = true)
    {
        $html = '<script type="text/javascript" src="' . $src . '"></script>' . "\n";
        if(true === $echo) {
            echo $html;
        } else {
            return $html;
        }
    }
    
    function addCss($src, $rel = "stylesheet", $echo = true)
    {
        $html = '<link href="' . $src . '" rel="' . $rel . '" type="text/css" />' . "\n";
        if(true === $echo) {
            echo $html;
        } else {
            return $html;
        }
    }
    
    function addImg($src, $params = array(), $echo = true)
    {
        $attributs = '';
        if (count($params)) {
            foreach ($params as $key => $value) {
                $attributs .= " $key=\"$value\"";
            }
            $attributs .= " ";
        }
        $html = '<img src="' . $src . '"' . $attributs . ' />' . "\n";
        echo $html;
        if(true === $echo) {
            echo $html;
        } else {
            return $html;
        }
    }
    
    function makePassword($size = 9)
	{
		$data = array();
			
		for ($i = 'a' ; $i <= 'z', strlen($i) == 1 ; $i++) {
			$data[] = $i;
		}
        
		for ($i = 0 ; $i <= 9 ; $i++) {
			$data[] = $i;
		}
        
		shuffle($data);
			
		$password = '';
			
		$nb = count($data) - 1;
			
		while (strlen($password) < $size) {
			$rand = rand(0, $nb);
			$password .= $data[$rand];
			shuffle($data);
		}
		return $password;
	}
    
    function pdfUrl($html, $portrait = false)
	{
		$data = "html=" . urlencode($html);
		$ch = curl_init('http://www.phpqc.com/makepdf.php');
		curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		$url = curl_exec($ch);
		curl_close($ch);
		// die($url);
		$orientation = ($portrait == true) ? 'Portrait' : 'Landscape';
		
		$purl = 'http://www.webz0ne.com/api/pdf.php?url=' . urlencode($url) . '&orientation=' . $orientation;
		$pdf = file_get_contents($purl);
		
		$fic = DIR_TMP . md5($html) . '.pdf';
		@unlink($fic);
		@touch($fic);
		@chmod($fic, 0777);
		file_put_contents($fic, $pdf);
		return $fic;
	}
    
    function codebarre($str)
    {
		return '<img src="http://trousses.ymp-pmj.ca/wrapper.php?p_bcType=1&p_text=' . sl($str) . '&p_xDim=1&p_w2n=3&p_charGap=2&p_invert=Y&p_charHeight=50&p_type=2&p_label=N&p_rotAngle=0&p_checkDigit=Y" />';
	}
    
    function makePdf($url, $orientation = 'Landscape')
	{
		$pdfUrl = 'http://www.webz0ne.com/api/pdf.php?url=' . urlencode($url) . '&orientation=' . $orientation;
        $pdf = file_get_contents($pdfUrl);
		return $pdf;
	}
    
    function printPage($url, $orientation = 'Landscape', $name = 'Impression')
    {
        $pdf = makePdf($url, $orientation);
        
		header ("Content-type: application/pdf");
		header ('Content-disposition: attachement; filename="' . $name . '.pdf"');
		header("Content-Transfer-Encoding: binary");
		header("Expires: 0");
		header("Cache-Control: no-cache, must-revalidate");
		header("Pragma: no-cache");
		die($pdf);
    }
    
    function mel($to, $subject, $body, $from, $isHtml = false)
    {
        $mailFormat = (!$isHtml) ? 'text' : 'html';
        
        $mailOptions = array(
            'mailToAddress' => $to,
            'mailToName' => $to,
            'mailFromAddress' => $from,
            'mailFromName' => $from,
            'mailFormat' => $mailFormat,
            'mailSubject' => $subject,
            'mailIso' => 'ISO-8859-1',
            'mailPriority' => 3,
            'mailXMailer' => 'Apple Mail (2.936)'
        );
        
        if (!$isHtml) {
            $mailOptions['mailTxt'] = $body;
        } else {
            $mailOptions['mailHtml'] = $body;
        }
        
        return mailJet($mailOptions);
    }
    
    function mailJet($mailOptions)
    {
        if (!is_array($mailOptions)) {
            return false;
        }
        
        // $mailOptions = array(
            // 'mailToAddress' => 'gplusquellec@free.fr',
            // 'mailToName' => 'Gerald',
            // 'mailFromAddress' => 'info@webz0ne.com',
            // 'mailFromName' => 'info@webz0ne.com',
            // 'mailFormat' => 'text/html',
            // 'mailSubject' => 'test',
            // 'mailTxt' => 'test',
            // 'mailAttachments' => array('file1', 'file2'),
            // 'mailHtml' => 'test',
            // 'mailIso' => 'ISO-8859-1',
            // 'mailPriority' => 3,
            // 'mailXMailer' => 'Apple Mail (2.936)'
        // );
        
        if (!isset($mailOptions['mailToAddress']) || !isset($mailOptions['mailFromAddress']) || !isset($mailOptions['mailSubject'])) {
            return false;
        }
        
        if (!isEmail($mailOptions['mailToAddress']) || !isEmail($mailOptions['mailFromAddress'])) {
            return false;
        }
        
        extract($mailOptions);
        
        if (!isset($mailTxt) && !isset($mailHtml)) {
            return false;
        }
        
        if (!isset($mailXMailer)) {
            $mailXMailer = 'Apple Mail (2.936)';
        }
        
        if (!isset($mailPriority)) {
            $mailPriority = 3;
        }
        
        if (!isset($mailIso)) {
            $mailIso = 'ISO-8859-1';
        }
        
        if (!isset($mailToName)) {
            $mailToName = $mailToAddress;
        }
        
        if (!isset($mailFromName)) {
            $mailFromName = $mailFromAddress;
        }
        
        $config = array(
            'auth' => 'login',
			'username' => config('mailjet.publicKey'),
			'password' => config('mailjet.privateKey'),
			'ssl' => 'tls',
			'auth' => 'login',
			'port' => '587'
    	);
 
        $transport = new Zend_Mail_Transport_Smtp('in.mailjet.com', $config);
        $mail = new Zend_Mail($mailIso);
        
        if (isset($mailAttachments) && count($mailAttachments)) {
            foreach ($mailAttachments as $mailAttachment) {
                attachFileMail($mailAttachment, $mail);
            }
        }
        
        $mail->addHeader('X-Mailer', $mailXMailer);
        $mail->addHeader('Priority', $mailPriority);
        if (isset($mailTxt)) {
            $mail->setBodyText($mailTxt);
        }
        if (isset($mailHtml)) {
            $mail->setBodyHtml($mailHtml);
        }
        $mail->setFrom($mailFromAddress, $mailFromName);
        $mail->addTo($mailToAddress, $mailToName);
        $mail->setSubject($mailSubject);
        return $mail->send($transport);
    }
    
    function attachFileMail($file, $mail)
    {
        $myFile = file_get_contents($file);
        $nameTab = explode('/', $file);
        $fileName = end($nameTab);
        $at = new Zend_Mime_Part($myFile);
        $at->type = 'image/gif';
        $at->disposition = Zend_Mime::DISPOSITION_INLINE;
        $at->encoding = Zend_Mime::ENCODING_BASE64;
        $at->filename = $fileName;
        $mail->addAttachment($at);
    }
    
    function addHook($hookName, $hookTime = 'beforeDisplay')
    {
        $hooks = getoption('__hooks__');
        if (null === $hooks)
            $hooks = array();
        if (!in_array($hookName, $hooks[$hookTime]))
            $hooks[$hookTime] = $hookName;
    }
    
    function camelize($str)
	{		
		$str = 'c' . strtolower(trim($str));
		$str = ucwords(preg_replace('/[\s_]+/', ' ', $str));
		return substr(str_replace(' ', '', $str), 1);
	}
    
    function underscore($str)
	{
		return preg_replace('/[\s]+/', '_', strtolower(trim($str)));
	}
    
    function humanize($str)
	{
		return ucwords(preg_replace('/[_]+/', ' ', strtolower(trim($str))));
	}
    
    
    function debug($obj)
    {
        Zend_Debug::dump($obj);
    }
    
    function session()
    {
        $sessionName = md5_file(__file__);
        $session = new Zend_Session_Namespace(SESSION_NAME);
        return $session;
    }
    
    function makeExcel($tab, $table)
	{
		$table = _r(' ', '_', $table);
		$excel = '<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">

	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
		<meta name="ProgId" content="Excel.Sheet">
		<meta name="Generator" content="Microsoft Excel 11">
		<style id="Classeur1_17373_Styles">
		<!--table
			{mso-displayed-decimal-separator:"\,";
			mso-displayed-thousand-separator:" ";}
		.xl1517373
			{padding-top:1px;
			padding-right:1px;
			padding-left:1px;
			mso-ignore:padding;
			color:windowtext;
			font-size:10.0pt;
			font-weight:400;
			font-style:normal;
			text-decoration:none;
			font-family:Arial;
			mso-generic-font-family:auto;
			mso-font-charset:0;
			mso-number-format:General;
			text-align:general;
			vertical-align:bottom;
			mso-background-source:auto;
			mso-pattern:auto;
			white-space:nowrap;}
		.xl2217373
			{padding-top:1px;
			padding-right:1px;
			padding-left:1px;
			mso-ignore:padding;
			color:#FFFF99;
			font-size:10.0pt;
			font-weight:700;
			font-style:normal;
			text-decoration:none;
			font-family:Arial, sans-serif;
			mso-font-charset:0;
			mso-number-format:General;
			text-align:center;
			vertical-align:bottom;
			background:#003366;
			mso-pattern:auto none;
			white-space:nowrap;}
		-->
		</style>
	</head>

		<body>
		<!--[if !excel]>&nbsp;&nbsp;<![endif]-->

		<div id="Classeur1_17373" align="center" x:publishsource="Excel">

		<table x:str border="0" cellpadding="0" cellspacing="0" width=640 style="border-collapse:
		 collapse; table-layout: fixed; width: 480pt">
		 <col width="80" span=8 style="width: 60pt">
		 <tr height="17" style="height:12.75pt">
		  ##entetes##
		 </tr>
		 ##contenu##
		</table>
		</div>
	</body>
</html>';
		$tpl_entete = '<td class="xl2217373">##val##</td>';
		$tpl_td = '<td>##val##</td>';
		
		$entetes = array();
		
		foreach ($tab as $ligne) {
			foreach ($ligne as $c => $v) {
				if (!in_array($c, $entetes))
					$entetes[] = $c;
			}
		}
		$ent_xls = '';
		foreach ($entetes as $ent)
			$ent_xls .= _r('##val##', $ent, $tpl_entete);
		$excel = _r('##entetes##', $ent_xls, $excel);
		
		$cont_xls = '';
		foreach ($tab as $ligne) {
			$cont_xls .= '<tr>';
			foreach ($ligne as $c => $v) {
				if (is_utf8($v))
                    $v = utf8_decode($v);
                $cont_xls .= _r('##val##', $v, $tpl_td);
            }
			$cont_xls .= '</tr>';
		}
		
		$excel = _r('##contenu##', $cont_xls, $excel);
		header ("Content-type: application/excel");
		header ('Content-disposition: attachement; filename="export_' . $table . '_' . date('d_m_Y_H_i_s') . '.xls"');
		header("Content-Transfer-Encoding: binary");
		header("Expires: 0");
		header("Cache-Control: no-cache, must-revalidate");
		header("Pragma: no-cache");
		die($excel);
	}
    
    function getInstance($className, $params = '')
    {
        $instance = $className::getInstance($params);
        return $instance;
    }
    
    function zend()
    {
        require_once 'Zend/Loader/Autoloader.php';
        $autoloader = Zend_Loader_Autoloader::getInstance();
        $autoloader->setFallbackAutoloader(true);
    }
    
    function viewRenderer($files = array())
    {
        if (!count($files)) {
            $files = array(
				tpl()
            );
        }
        setvar('**htmlFiles**', $files);
    }
    
    function go404()
    {
        setvar('**page**', 404);
        setvar('**action**', 'index');
        $controller = controller::getInstance();
        $htmlFiles = array(
				tpl()
			);
        setvar('**htmlFiles**', $htmlFiles);
        $controller->html();
        exit;
    }
    
    function tpl()
    {
        $htmlPage = getvar('**page**') . '/';
        if (getvar('**action**') !== null) {
           $htmlPage .= getvar('**action**');
        }
        if (!is_file(DIR_VIEWS . $htmlPage . '.html')) {
            go404();
        }
        return $htmlPage;
    }
    
    function isEmail($email)
    {
        return Zend_Validate::is($email, 'EmailAddress');
    }
    
    function cache($name, $value = '')
    {
        $fo = array(
            'lifetime' => 7200,
            'automatic_serialization' => true
        );
        
        $bo = array(
            'cache_dir' => DIR_CACHE
        );
        
        $cache = Zend_Cache::factory(
            'Core',
            'File',
            $fo,
            $bo
        );
        
        $cached = $cache->load($name);
        
        if (false === $cached && !empty($value)) {
            $cache->save($value, $name);
            return $value;
        }
        if (false === $cached && empty($value))
            return false;
        return $cached;
    }
    
    
    function putFunctionCache($fonction, $param = '')
	{
		if (is_array($param)) {
			$res = call_user_func_array($fonction, $param);
			$param = implode(', ', $param);
		} else
			$res = $fonction($param);
        $name = md5($fonction . $param);
        cache($name, $res);
		return $res;
	}
	
	function callFunctionCache($fonction, $param = '')
	{
		if (is_array($param))
			$params = implode(', ', $param);
		$name = md5($fonction . $params);
        $cached = cache($name);
        if (false === $cached)
            return putFunctionCache($fonction, $param);
        else
            return $cached;
	}
    
    
    //formulaires
    function initCssForm()
    {
        $css = array(
                'ViewHelper',
                'Errors',
                array('HtmlTag', array('tag' => 'td')),
                array('Label', array('tag' => 'th')),
                array(array('tr' => 'HtmlTag'), array('tag' => 'tr'))
            );
        setvar('**cssForm**', $css);
    }
    
    function formHidden($form, $name, $value = '')
    {
        $$name = new Zend_Form_Element_Hidden($name);
        $$name->setValue($value);
        $$name->setAttrib('class', 'hidden');
        $$name->setDecorators(getvar('**cssForm**'));
        $form->addElement($$name);
    }
    
    function formInput($form, $name, $label = '', $required = true, $value = '')
    {
        if (!strlen($label))
            $label = $name;
        $$name = new Zend_Form_Element_Text($name);
        $$name->setValue($value);
        $$name->setAttrib('class', 'text');
        $$name->setLabel(__($label));
        $$name->setRequired($required);
        $$name->addValidator('NotEmpty', 0, array('messages' => __('Merci de renseigner ce champ.')));
        $$name->setDecorators(getvar('**cssForm**'));
        $form->addElement($$name);
    }
    
    function formDate($form, $name, $label = '', $required = true, $value = '')
    {
        if (!strlen($label))
            $label = $name;
        $$name = new Zend_Form_Element_Text($name);
        $$name->setValue($value);
        $$name->setAttrib('class', 'text date_picker');
        $$name->setLabel(__($label));
        $$name->setRequired($required);
        $$name->addValidator('NotEmpty', 0, array('messages' => __('Merci de renseigner ce champ.')));
        $$name->setDecorators(getvar('**cssForm**'));
        $form->addElement($$name);
    }
    
    function formPassword($form, $name, $label = '', $required = true, $value = '')
    {
        if (!strlen($label))
            $label = $name;
        $$name = new Zend_Form_Element_Password($name);
        $$name->setValue($value);
        $$name->setAttrib('class', 'text');
        $$name->setLabel(__($label));
        $$name->setRequired($required);
        $$name->addValidator('NotEmpty', 0, array('messages' => __('Merci de renseigner ce champ.')));
        $$name->setDecorators(getvar('**cssForm**'));
        $form->addElement($$name);
    }
    
    function formHtml($form, $name, $label = '', $required = true, $value = '')
    {
        if (!strlen($label))
            $label = $name;
        $$name = new Zend_Form_Element_Textarea($name);
        $$name->setValue($value);
        $$name->setLabel(__($label));
        $$name->setAttrib('class', 'wysiwygTiny');
        $$name->setRequired($required);
        $$name->addValidator('NotEmpty', 0, array('messages' => __('Merci de renseigner ce champ.')));
        $$name->setDecorators(getvar('**cssForm**'));
        $form->addElement($$name);
    }
    
    function formTextarea($form, $name, $label = '', $required = true, $value = '')
    {
        if (!strlen($label))
            $label = $name;
        $$name = new Zend_Form_Element_Textarea($name);
        $$name->setValue($value);
        $$name->setLabel(__($label));
        $$name->setRequired($required);
        $$name->addValidator('NotEmpty', 0, array('messages' => __('Merci de renseigner ce champ.')));
        $$name->setDecorators(getvar('**cssForm**'));
        $form->addElement($$name);
    }
    
    function formSelect($form, $name, $label = '', $required = true, $value = array())
    {
        if (!strlen($label))
            $label = $name;
        $$name = new Zend_Form_Element_Select($name);
        $$name->addMultiOptions($value);
        $$name->setLabel(__(aff_fo($label)));
        $$name->setAttrib('class', 'styled');
        $$name->setRequired($required);
        $$name->addValidator('NotEmpty', 0, array('messages' => __('Merci de renseigner ce champ.')));
        $$name->setDecorators(getvar('**cssForm**'));
        $form->addElement($$name);
    }
    
    //
    
    function sanitForm($form)
    {
        $form = _r('<ul class="errors">', '<tr><td  colspan="2" class="errorForm">', $form);
        $form = _r('</ul>', '</td></tr>', $form);
        $form = _r('<li>', '', $form);
        $form = _r('</li>', '&nbsp;', $form);
        $form = _r('<dt id="challenge-label">&#160;</dt>', '', $form);
        $form = _r('<dd id="challenge-element">', '<tr><td  colspan="2">', $form);
        $form = _r('</dd>', '</td></tr>', $form);
        return $form;
    }
    
    function sanitsql($str)
	{
		if (strstr($str, '##')) {
			$str = _r('##', '', $str);
			switch ($str) {
				case 'now':
					$str = _r('now', 'NOW()', $str);
					break;
				default:
					$str = getvar($str);
					break;
			}
		}
        return addslashes($str);
	}
    
    function optionsPage($default)
    {
        $page = getvar('**page**');
        $limit = config('limit');
        
        $numPage = getvar('__numPage_' . $page . '__');
        if (null === $numPage) {
            $numPage = getvarget('numPage_' . $page);
            if (null === $numPage) {
                $numPage = getvarpost('numPage_' . $page);
                if (null === $numPage)
                    $numPage = getoption('numPage_' . $page);
            }
        }
        
        $order = getvar('__order_' . $page . '__');
        // die($order);
        if (null === $order) {
            $numPage = getvarget('order_' . $page);
            if (null === $order) {
                $order = getvarpost('order_' . $page);
                if (null === $order)
                    $order = getoption('order_' . $page);
            }
        }
        
        $sens = getvar('__sens_' . $page . '__');
        if (null === $sens) {
            $numPage = getvarget('sens_' . $page);
            if (null === $sens) {
                $sens = getvarpost('sens_' . $page);
                if (null === $sens)
                    $sens = getoption('sens_' . $page);
            }
        }
        
        if (null === $numPage)
            $numPage = 1;
        if (null === $order)
            $order = $default;
        if (null === $sens)
            $sens = 'ASC';
            
        $start = ($numPage * $limit) - $limit;
        
        setoption('numPage_' . $page, $numPage);
        setoption('order_' . $page, $order);
        setoption('sens_' . $page, strtolower($sens));
        setoption('start_' . $page, $start);
        
        return array($numPage, $order, $sens, $start);
    }
    
    function makeOrder($field)
    {
        $page = getvar('**page**');
        $action = getvar('**action**');
        
        $sens = getoption('sens_' . $page);
        $numPage = getoption('numPage_' . $page);
        $order = getoption('order_' . $page);
        $start = getoption('start_' . $page);
        
        if ($field == $order) {
            $img = URL_SITE . 'img/sort_' . $sens . '.png';
            $sensUrl = ($sens == 'asc') ? 'desc' : 'asc';
        } else {
            $img = URL_SITE . 'img/sort_both.png';
            $sensUrl = 'asc';
        }
        
        $options = array(
            'numPage_' . $page => $numPage,
            'order_' . $page => $field,
            'sens_' . $page => $sensUrl,
            'start_' . $page => $start
        );
        
        $url = makeUrl($page, $action, $options);
        $html = '<a href="' . $url . '"><img style="position: relative; top: 3px; left: 3px;" border="0" src="' . $img. '" alt="' . __('Ordonner') . '" title="' . __('Ordonner') . '" /></a>';
        return $html;
    }
    
    function insertDb($table, $tab)
	{
		$db = db();
		if (is_array($tab)) {
			$q = "INSERT INTO $table SET datecrea = NOW(), datemodif = NOW(), ";
			foreach ($tab as $c => $v) {
                if (strlen($v)) {
                    $q .= "$c = '" . sanitsql($v) . "', ";
                }
            }
            $q = substr($q, 0, -2);
			$db->requete($q);
			return true;
		}
		return false;
	}
	
	function updateDb($table, $tab, $where = '1 = 1')
	{
		$db = db();
		if (is_array($tab)) {
			$q = "UPDATE $table SET datemodif = NOW(), ";
			foreach ($tab as $c => $v) {
				$q .= "$c = '" . sanitsql($v) . "', ";
			}
            $q = substr($q, 0, -2);
			$q .= ' WHERE ' . $where;
			$db->requete($q);
			return true;
		}
		return false;
	}
	
	function updateDbId($table, $tab, $id)
	{
		return updateDb($table, $tab, 'id = ' . $id);
	}
	
	function deleteDb($table, $where = '1 = 1')
	{
		$db = db();
		$q = "DELETE FROM $table WHERE " . $where;
		$db->requete($q);
		return true;
	}
	
	function deleteDbId($table, $id)
	{
		return deleteDb($table, 'id = ' . $id);
	}
	
	function emptyTable($table)
	{
		$db = db();
		$db->requete("TRUNCATE TABLE $table");
		return true;
	}
    
    function appsession()
    {
        Zend_Session::start();
    }
    
    function form($class)
    {
        if (is_file(DIR_MODELS . 'forms/' . $class . '.php')) {
            require_once(DIR_MODELS . 'forms/' . $class . '.php');
            $form = new $class;
            return $form;
        }
        return null;
    }
    
    function instantiate($class, $record) 
    {
		$object = new $class;
		
		foreach($record as $attr => $val) {
            if(has_attribute($object, $attr)) {
				$object->$attr = $val;
            }
		}
        return $object;
	}
    
    function has_attribute($class, $attribute) 
    {
		$object_vars = get_object_vars($class);
		return array_key_exists($attribute, $object_vars);
	}
    
    function purgeCache($force = false)
	{
		emptyDirectory(DIR_CACHE, $force);
	}
	
    function purgeFiles($force = false)
	{
		emptyDirectory(DIR_FILES, $force);
	}
	
	function purgeOptions($force = false)
	{
        emptyDirectory(DIR_OPT, $force);
	}
    
    function emptyDirectory($dir, $force = false)
    {
        if (false === $force) {
            $expire = config("timeCache");
        } else {
            $expire = 0;
        }
        
        if (is_dir($dir)) {
			$objects = scandir($dir);
			foreach ($objects as $object) {
				if ($object <> "." && $object <> "..") {
					if (filetype($dir . DIRECTORY_SEPARATOR . $object) == "dir") 
						emptyDirectory($dir . DIRECTORY_SEPARATOR . $object, $force); 
					else {
						$now = time();
						$age = filemtime($dir . DIRECTORY_SEPARATOR . $object);
						$diff = $now - $age;
                        if ($diff >= $expire)
							@unlink($dir . DIRECTORY_SEPARATOR . $object);
					}
				}
			}
			reset($objects);
		}
    }
    
    function post($url, $data)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $page = curl_exec($ch);
        curl_close($ch);
        return $page;
    }
    
    function push($url, $data)
    {
        $urlPush = $url;
        $suite = '';
        foreach ($data as $key => $value)
            $suite .= $key . '=' . urlencode($value) . '&';
        $suite = substr($suite, 0, -1);
        $urlPush .= '?' . $suite;
        return file_get_contents($urlPush);
    }
    
    function mediaLink($id)
    {
        return 'http://01php.fr/mu/?d=' . $id;
    }
    
    function media($url, $name = '', $del = 1)
    {
        if (!isset($name))
            $name = md5($url);
        $urlPost = 'http://www.webz0ne.com/api/bigfile.php';
        $data = array(
            'url' => $url,
            'name' => $name,
            'del' => $del
        );
        $urlBack = post($urlPost, $data);
        if (strstr($urlBack, 'd=')) {
            $urlBack = _r("\n", "", $urlBack);
            $urlBack = _r("\r", "", $urlBack);
            $urlBack = _r("\t", "", $urlBack);
            list($dummy, $code) = explode('d=', $urlBack, 2);
            return $code;
        }
        return false;
    }
    
    function mediaDown($code)
    {
        $file = file_get_contents('http://www.01php.fr/mu/?d=' . $code);
        return $file;
    }
    
    function mediaUrl($code)
    {
        return file_get_contents('http://www.01php.fr/mu/?u=1&d=' . $code);
    }
    
    function mediaStream($code)
    {
        $url = mediaUrl($code);
        $extTab = explode('.', $url);
        $nameTab = explode('/', $url);
        $ext = end($extTab);
        $name = end($nameTab);
        $name = _r('.' . $ext, '', $name);
        $size = ffilesize($url);
        
        header("Content-Type: application/$ext; name=\"$name\"");
        header("Content-Transfer-Encoding: binary");
        header("Content-Disposition: attachment; filename=\"$name\"");
        header('Content-Length: ' . $size);
        header("Expires: 0");
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
        ob_clean();
        flush();
        readfile($url);
        exit;
    }
    
    function ffilesize($file)
	{
		$ch = curl_init($file);
		curl_setopt($ch, CURLOPT_NOBODY, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HEADER, true);
		$data = curl_exec($ch);
		curl_close($ch);
		if ($data === false)
			return false;
		if (preg_match('/Content-Length: (\d+)/', $data, $matches))
			return (float)$matches[1];
	}
    
    function cacheDb()
    {
        $cache = GP_dbcache::getInstance();
        return $cache;
    }
    
    function model($model)
    {
        $file = DIR_MODELS . $model . '.ini';
        if (is_file($file)) {
            $ini = new Zend_Config_Ini($file);
            return explode(',', $ini->fields);
        }
        return array();
    }
    
    function attrField($model, $field, $attribut)
    {
        $file = DIR_MODELS . $model . '.ini';
        if (is_file($file)) {
            $ini = new Zend_Config_Ini($file);
            return $ini->$field->$attribut;
        }
        return null;
    }
    
    function compressFile($file, $data)
    {
        @touch($file);
        @chmod($file, 0777);
        $gzdata = gzencode($data, 9);
        $fp = fopen($file, "a");
        fwrite($fp, $gzdata);
        fclose($fp);
    }
    
    function GPmail($to, $subject, $body, $from)
    {
        $mail = new Zend_Mail();
        $mail->addHeader('X-Mailer', 'Apple Mail (2.936)');
        $mail->setBodyText($body);
        $mail->setBodyHtml($body);
        $mail->setFrom($from);
        $mail->addTo($to);
        $mail->setSubject($subject);
        $res = $mail->send();
        return $res;
    }
    
    function dbDoc($dbName, $dbColl)
    {
        $db = new GP_mongo('mongodb://' . CACHE_DB_USER . ':' . CACHE_DB_PASSWORD . '@' . CACHE_DB_HOST);
        $db->db($dbName);
        $db->coll($dbColl);
        return $db;
    }
    
    function dbCache()
    {
        $db = new GP_mongo('mongodb://' . CACHE_DB_USER . ':' . CACHE_DB_PASSWORD . '@' . CACHE_DB_HOST);
        $db->db(CACHE_DB_NAME);
        $db->coll(CACHE_DB_COLLECTION);
        return $db;
    }
    
    function cleanDbCache()
    {
        $db = dbCache();
        $min = time() - CACHE_DB_CACHETIME;
        $dateMin = array('$lt' => $min);
        return $db->delete(array("timeAdd" => $dateMin));
    }
    
    function setDbCache($name, $value)
    {
        $db = dbCache();
        $ids = session_id();
        $db->delete(array("session" => $ids, 'option' => $name));
        $db->insert(array('session' => $ids, 'option' => $name, 'value' => $value));
    }
    
    function getDbCache($name)
    {
        $db = dbCache();
        $ids = session_id();
        $q = array();
        $q['queries'][] = array('session', '=', $ids);
        $q['queries'][] = array('option', '=', $name);
        $q['operators'][] = '&&';
        $res = $db->query($q);
        if (count($res))
            foreach ($res as $record)
                return $record['value'];
        return null;
    }
	
	function load($className)
    {
        $dirClass = DIR_LIB . 'gp/class.' . $className . '.php';
        if (is_file($dirClass))
            require_once($dirClass);
    }
    
    function acc($str, $charset = 'utf-8')
	{
		$str = htmlentities($str, ENT_NOQUOTES, $charset);
		
		$str = preg_replace('#&([A-za-z])(?:acute|cedil|circ|grave|orn|ring|slash|th|tilde|uml);#', '\1', $str);
		$str = preg_replace('#&([A-za-z]{2})(?:lig);#', '\1', $str); // pour les ligatures e.g. '&oelig;'
		$str = preg_replace('#&[^;]+;#', '', $str); // supprime les autres caractères
		return $str;
	}
    
    function go($url)
    {
        if (!headers_sent()) {
			header('Location: ' . $url);
			exit;
		} else {
			echo '<script type="text/javascript">';
			echo "\t" . 'window.location.href = "' . $url . '";';
			echo '</script>';
			echo '<noscript>';
			echo "\t" . '<meta http-equiv="refresh" content="0;url=' . $url . '" />';
			echo '</noscript>';
			exit;
		}
    }
    
    function purge()
    {
        $purgeFile = DIR_TMP . 'purge.txt';
        if (!is_file($purgeFile))
            touch($purgeFile, 0777);
        $max = 43200; // 12 heures
        $age = filemtime($purgeFile);
        $diff = time() - $age;
        if ($diff >= $max) {
            purgeCache(true);
            purgeOptions(true);
            purgeFiles(true);
            unlink($purgeFile);
            touch($purgeFile, 0777);
            file_put_contents($purgeFile, time());
        }
    }
    
    function connexion($login, $mdp)
    {
        $db = db();
        $q = "SELECT * FROM users WHERE login = '" . addslashes($login) . "' && mdp = '" . $mdp . "'";
        $res = $db->fetchArray_one($q);
        if (count($res)) {
            $user = new stdClass;
            $user->uid = md5(uniqid(php_uname('n'), true));
            $user->sessionId = session_id();
            foreach ($res as $key => $value)
                $user->$key = $value;
            setoption('__user__', $user);
            return true;
        }
        return false;
    }
    
    function verifToken()
    {
        $token = token();
        $postToken = getvarpost('token');
        if ($token == $postToken)
            return true;
        return false;
    }
    
    function addCaptcha($form)
    {
        $seg = '<tr><td colspan="2">
<input type="submit"';

        $replace = '<tr><th id="captcha-label"><label for="captcha" class="required">'.__('Vérification').'</label></th><td>' . captcha() . '</td></tr>' . $seg;
        $form = _r($seg, $replace, $form);
        $js = "<script>
	var RecaptchaOptions = 
	{
	  theme : 'clean',
	  lang : 'fr'
	};
	</script>";
        return $js . $form;
    }
    
    function captcha()
    {
        $config = getConfig();
        $publicKey = $config['reCaptcha.publicKey'];
        $captcha = recaptcha_get_html($publicKey);
        return $captcha;
    }
    
    function verifyCaptcha()
    {
        $config = getConfig();
        $privateKey = $config['reCaptcha.privateKey'];
        $verify = recaptcha_check_answer (
			$privateKey,
            $_SERVER["REMOTE_ADDR"],
            $_POST['recaptcha_challenge_field'],
            $_POST['recaptcha_response_field']
		);
        
        return $verify->is_valid;
    }  
    
    
    function user()
    {
        $user = getoption('__user__');
        if (null === $user)
            return session_id();
        return $user;
    }
    
    function role()
    {
        return getUser('role');
    }
    
    function idUser()
    {
        return getUser('id');
    }
    
    function token()
    {
        return getUser();
    }
    
    function getUser($param = 'uid')
    {
        $user = user();
        if (is_object($user))
            return $user->$param;
        return null;
    }
    
    function aff_fo($chaine)
	{
		if (!is_utf8($chaine))
			$chaine = utf8_encode($chaine);
		return sl($chaine);
	}
    
    function cleanString($chaine)
	{
		$chaine = strtolower($chaine);
		$chaine = acc($chaine);
		
		$chaine = _r(" ", '_', $chaine);
		$chaine = _r("'", '_', $chaine);
		$chaine = _r("(", '_', $chaine);
		$chaine = _r(")", '_', $chaine);
		$chaine = _r(";", '_', $chaine);
		$chaine = _r(",", '_', $chaine);
		$chaine = _r(":", '_', $chaine);
		$chaine = _r("!", '_', $chaine);
		$chaine = _r(".", '_', $chaine);
		$chaine = _r("?", '_', $chaine);
		$chaine = _r("/", '_', $chaine);
		$chaine = _r("*", '_', $chaine);
		$chaine = _r("-", '_', $chaine);
		$chaine = _r("+", '_', $chaine);
		$chaine = _r("[", '_', $chaine);
		$chaine = _r("]", '_', $chaine);
		$chaine = _r("{", '_', $chaine);
		$chaine = _r("}", '_', $chaine);
		$chaine = _r("=", '_', $chaine);
		$chaine = _r("@", '_', $chaine);
		$chaine = _r("#", '_', $chaine);
		
		$chaine = _r("_039_", '_', $chaine);
		$chaine = _r("_00128_", 'euro', $chaine);
		$chaine = _r("_00192_", 'a', $chaine);
		$chaine = _r("_00193_", 'a', $chaine);
		$chaine = _r("_00194_", 'a', $chaine);
		$chaine = _r("_00195_", 'a', $chaine);
		$chaine = _r("_00196_", 'a', $chaine);
		$chaine = _r("_00197_", 'a', $chaine);
		$chaine = _r("_00198_", 'a', $chaine);
		$chaine = _r("_00224_", 'a', $chaine);
		$chaine = _r("_00225_", 'a', $chaine);
		$chaine = _r("_00226_", 'a', $chaine);
		$chaine = _r("_00227_", 'a', $chaine);
		$chaine = _r("_00228_", 'a', $chaine);
		$chaine = _r("_00229_", 'a', $chaine);
		$chaine = _r("_00230_", 'a', $chaine);
		
		$chaine = _r("_00209_", 'n', $chaine);
		$chaine = _r("_00241_", 'n', $chaine);
		
		$chaine = _r("_00223_", 'ss', $chaine);
		
		$chaine = _r("_00199_", 'c', $chaine);
		$chaine = _r("_00231_", 'c', $chaine);
		
		$chaine = _r("_00201_", 'e', $chaine);
		$chaine = _r("_00232_", 'e', $chaine);
		$chaine = _r("_00200_", 'e', $chaine);
		$chaine = _r("_00202_", 'e', $chaine);
		$chaine = _r("_00203_", 'e', $chaine);
		$chaine = _r("_00233_", 'e', $chaine);
		$chaine = _r("_00234_", 'e', $chaine);
		$chaine = _r("_00235_", 'e', $chaine);
		
		$chaine = _r("_00204_", 'i', $chaine);
		$chaine = _r("_00205_", 'i', $chaine);
		$chaine = _r("_00206_", 'i', $chaine);
		$chaine = _r("_00207_", 'i', $chaine);
		$chaine = _r("_00236_", 'i', $chaine);
		$chaine = _r("_00237_", 'i', $chaine);
		$chaine = _r("_00238_", 'i', $chaine);
		$chaine = _r("_00239_", 'i', $chaine);
		
		$chaine = _r("_00210_", 'o', $chaine);
		$chaine = _r("_00211_", 'o', $chaine);
		$chaine = _r("_00212_", 'o', $chaine);
		$chaine = _r("_00213_", 'o', $chaine);
		$chaine = _r("_00214_", 'o', $chaine);
		$chaine = _r("_00216_", 'o', $chaine);
		$chaine = _r("_00240_", 'o', $chaine);
		$chaine = _r("_00241_", 'o', $chaine);
		$chaine = _r("_00242_", 'o', $chaine);
		$chaine = _r("_00243_", 'o', $chaine);
		$chaine = _r("_00244_", 'o', $chaine);
		$chaine = _r("_00245_", 'o', $chaine);
		$chaine = _r("_00246_", 'o', $chaine);
		$chaine = _r("_00248_", 'o', $chaine);
		
		$chaine = _r("_00217_", 'u', $chaine);
		$chaine = _r("_00218_", 'u', $chaine);
		$chaine = _r("_00219_", 'u', $chaine);
		$chaine = _r("_00220_", 'u', $chaine);
		$chaine = _r("_00249_", 'u', $chaine);
		$chaine = _r("_00250_", 'u', $chaine);
		$chaine = _r("_00251_", 'u', $chaine);
		$chaine = _r("_00252_", 'u', $chaine);
		
		$chaine = _r("_00221_", 'y', $chaine);
		$chaine = _r("_00253_", 'y', $chaine);
		$chaine = _r("_00254_", 'y', $chaine);
		$chaine = _r("_00255_", 'y', $chaine);
		
		$chaine = _r("__", '_', $chaine);
		$chaine = _r("__", '_', $chaine);
		$chaine = _r("__", '_', $chaine);
		
		$last = $chaine[strlen($chaine) - 1];
		if ($last == '_')
			$chaine = substr($chaine, 0, -1);
		return $chaine;
	}
    
    function __($str)
    {
        $lng = getoption('__lng__');
        if (false === $lng || null === $lng) {
            $lng = LNG_DEFAULT;
        }
        $lngDefault = LNG_DEFAULT;
        if ($lng == $lngDefault) {
            $strTab = explode('[[', $str);
            for ($i = 1 ; $i < count($strTab) ; $i++) {
                $seg = trim($strTab[$i]);
                list($var, $dummy) = explode(']]', $seg, 2);
                $str = _r("[[$var]]", getvar($var), $str);
            }
            return $str;
        }
        return callFunctionCache('cacheTranslation', array($str, $lng));
    }
    
    
    function cacheTranslation($str, $lng)
    {
        $trad = new GP_trad($lng);
        $strTrans = $trad->__($str);
        $strTab = explode('[[', $strTrans);
        for ($i = 1 ; $i < count($strTab) ; $i++) {
            $seg = trim($strTab[$i]);
            list($var, $dummy) = explode(']]', $seg, 2);
            $strTrans = _r("[[$var]]", getvar($var), $strTrans);
        }
        return $strTrans;
    }
    
    function db()
    {
        $config = getConfig();
        $db = new GP_db($config['db.dsn'], $config['db.user'], $config['db.password']);
        return $db;
    }
    
    function getConfig()
    {
        return getvar('**config**');
    }
	
	function setvar($nom, $val, $force = true)
	{
		$gp_options = GP_options::getInstance();
		if (true === $force) {
			$gp_options->delete($nom);
			$gp_options->record($nom, $val);
		}
		return true;
	}
    
    function getvartab($tabName, $key)
    {
        $tab = getvar($tabName);
        if (is_array($tab) && count($tab) && null !== $tab)
            if (isset($tab[$key]))
                return $tab[$key];
        return null;
    }
	
	function getvar($nom)
	{
		$gp_options = GP_options::getInstance();
		return $gp_options->get($nom);
	}
	
	function getvarpost($nom)
	{
		return getvar('post_' . $nom);
	}
	
	function getvarget($nom)
	{
		return getvar('get_' . $nom);
	}
	
	function getvarsession($nom)
	{
		return getvar('session_' . $nom);
	}
	
	function deloption($nom, $id = null)
	{
		$gp_options = GP_options::getInstance();
		return $gp_options->deloption($nom, $id);
	}
	
	function setoption($nom, $val, $id = null)
	{
		$gp_options = GP_options::getInstance();
		return $gp_options->setoption($nom, $val, $id);
	}
	
	function getoption($nom, $id = null)
	{
		$gp_options = GP_options::getInstance();
		return $gp_options->getoption($nom, $id);
	}
    
    function allVars()
    {
        $obj = new stdClass;
        $vars = GP_options::getInstance();
        $varsTab = get_object_vars($vars);
        foreach ($varsTab as $varName => $varValue) {
            if (strstr($varName, '**')) {
                $varName = _r('**', '', $varName);
                $obj->$varName = $varValue;
            }
            if (strstr($varName, '__')) {
                $varName = _r('__', '', $varName);
                $obj->$varName = $varValue;
            }
        }
        return $obj;
    }
	
	function dossier_options($fic)
	{
		$dossier = substr($fic, -3);
		if (!is_dir(DIR_OPT . $dossier)) {
			$oldumask = umask(0);
			mkdir(DIR_OPT . $dossier, 0777);
			umask($oldumask);
		}
		return $dossier . '/';
	}
	
	function get_post()
	{
		if(count($_POST)) {
			foreach ($_POST as $c => $v) {
				setvar('post_' . $c, $v);
            }
		}
	}
	
	function get_get()
	{
		if(count($_GET)) {
			foreach ($_GET as $c => $v) {
				setvar('get_' . $c, $v);
            }
		}
	}
	
	function get_session()
	{
		if(count($_SESSION)) {
			foreach ($_SESSION as $c => $v) {
				setvar('session_' . $c, $v);
            }
		}
	}
    
    function hidden($form, $name, $value)
    {
        $css = array(
            'ViewHelper',
            'Errors',
            array('HtmlTag', array('tag' => 'td')),
            array('Label', array('tag' => 'th')),
            array(array('tr' => 'HtmlTag'), array('tag' => 'tr'))
        );
        $hidden = new Zend_Form_Element_Hidden($name);
        $hidden->setValue($value);
        $hidden->setAttrib('class', 'hidden');
        $hidden->setDecorators($css);
        $form->addElement($hidden);
    }
	
	function get_vars()
	{
		get_post();
		get_get();
		get_session();
	}
    
    function getRoutes()
    {
        return parse_ini_file(DIR_CONFIG . 'routes.ini');
    }
    
    function getRoute($uri)
    {
        $routes = getRoutes();
        $countArgsUri = count(explode('/', $uri));
        foreach ($routes as $routeName => $routeValue) {
            if (strstr($routeName, '.route')) {
                $routeName = _r('.route', '', $routeName);
                $countArgsRoute = count(explode('/', $routeValue));
                if ($countArgsUri == $countArgsRoute) {
                    if ($routeValue == $uri) {
                        setvar('**routeName**', $routeName);
                        return getRouteByName($routeName);
                    } else {
                        $routeValue = _r('[:any]', '.+', _r('[:num]', '[0-9]+', $routeValue));
                        if (preg_match('#^' . $routeValue . '$#', $uri)) {
                            setvar('**routeName**', $routeName);
                            return getRouteByName($routeName);
                        }
                    }
                }
            }
        }
        return null;
    }

    function getRouteByName($name)
    {
        $return = array();
        $routes = getRoutes();
        foreach ($routes as $routeName => $routeValue) {
            if (strstr($routeName, $name . '.')) {
                $return[str_replace($name . '.', '', $routeName)] = $routeValue;
            }
        }
        return $return;
    }
    
    function setvarUri($uri, $route)
    {
        $tabUri = explode('/', $uri);
        for ($i = 0 ; $i < count($tabUri) ; $i++) {
            if (isset($route['param' . ($i + 1)])) {
                setvar('__' . $route['param' . ($i + 1)] . '__', $tabUri[$i]);
            }
        }
    }
    
    function addEmail($email)
    {
        $html = '<a href="mailto:' . $email .'">' . $email .'</a>';
        echo $html;
    }
    
    function setSeo($name, $val)
    {
        setvar('**seo' . ucfirst($name) . '**', $val);
    }
    
    function getSeo($name)
    {
        return getvar('**seo' . ucfirst($name) . '**');
    }
    
    function seo()
    {
        $title = config('seo.title');
        $description = config('seo.description');
        $keywords = config('seo.keywords');
        
        if (null === getSeo('title')) {
            setSeo('title', $title);
        }
        
        if (null === getSeo('description')) {
            setSeo('description', $description);
        }
        
        if (null === getSeo('keywords')) {
            setSeo('keywords', $keywords);
        } 
    }
    
    function isPage($page, $action)
    {
        $route = getRoute(getUri());
        if (null !== $route) {
            $actualPage = $route['controller'];
            $actualAction = $route['action'];
            
            if ($actualPage == $page && $actualAction == $action) {
                return true;
            }
        } else {
            if (PAGE_DEFAULT === $page && ACTION_DEFAULT === $action) {
                return true;
            }
        }
        return false;
    }
    
    function getUri()
    {
        $uri = substr($_SERVER['REQUEST_URI'], 1, strlen($_SERVER['REQUEST_URI']));
        if (strlen(config('root'))) {
            $uri = _r('/' . config('root'), '', $uri);
        }
        return $uri;
    }
    
	function getPage()
	{
        seo();
        if (true === IS_MAINTENANCE) {
            setvar('**page**', 'maintenance');
            setvar('**action**', 'index');
            return 'maintenance';
        }
        $uri = getUri();
        $route = getRoute($uri);
        if (null !== $route) {
            $page = $route['controller'];
            $action = $route['action'];
            setvarUri($uri, $route);
            if(true == config('authorized') && null === getoption("__user__") && $page <> 404 && $page <> 'forget' && $page <> 'login' && $page <> 'backup') {
                $action = 'index';
                $page = 'login';
            }
            setvar('**page**', $page);
            setvar('**action**', $action);
            return $page;
        }
        $uri = _r('.html', '', $uri);
        $tabUri = explode('/', '/' . $uri);
        $page = $tabUri[1];
        $action = $tabUri[2];
        if (count($tabUri) > 3) {
            for ($i = 3 ; $i < count($tabUri) ; $i += 2) {
				setvar('__' . $tabUri[$i] . '__', $tabUri[$i + 1]);
            }
        }
        
        if (!strlen($action)) {
            $action = 'index';
		}
        
        if (!strlen($page)) {
			$page = getvarpost('page');
			if (null === $page) {
				$page = getvarsession('page');
				if (null === $page) {
					$page = PAGE_DEFAULT;
					$action = ACTION_DEFAULT;
                }
			}
		}
        
        if ($page == 'index') {
			$page = PAGE_DEFAULT;
            $action = ACTION_DEFAULT;
		}
        if ($page <> 'logout') {
            $page = (true === page_exists($page)) ? $page : 404;
        }
        if(true == config('authorized') && null === getoption("__user__") && $page <> 404 && $page <> 'forget' && $page <> 'login') {
            $action = 'index';
            $page = 'login';
        }
		
        if ($page == 'logout') {
            $_SESSION = array();
            purgeOptions(true);
            $page = 'login';
        }
        
        setvar('**page**', $page);
        setvar('**action**', $action);
        return $page;
	}
    
    function shareThis()
    {
        $js = '<script type="text/javascript">var switchTo5x=true;</script>
        <script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script>
        <script type="text/javascript">stLight.options({publisher:\''.config('shareThis.publisher').'\'});</script>';
        echo $js;
    }
    
    function dump($bug, $exit = true)
    {
        Zend_Debug::dump($bug);
        if (true === $exit) {
            exit;
        }
    }
	
	function page_exists($page)
	{
        return (is_file(DIR_CONTROLLERS . $page . '.php')) ? true : false;
	}
	
	function addError($error)
	{
		$errors = getvar('_errorsMessages');
		if (null === $errors) {
			$errors = array();
		}
        $errors[] = $error;
		$errors = array_unique($errors);
		setvar('_errorsMessages', $errors);
	}
	
	function getErrors()
	{
		return getvar('_errorsMessages');
	}
	
	function addTrace($trace)
	{
		$traces = getvar('_tracesMessages');
		if (null === $traces) {
			$traces = array();
		}
        $traces[] = $trace;
		$traces = array_unique($traces);
		setvar('_tracesMessages', $traces);
	}
	
	function getTraces()
	{
		return getvar('_tracesMessages');
	}
	
	function _r($a, $b, $string)
	{
		return str_replace($a, $b, $string);
	}
	
	function sl($string)
	{
		return stripslashes($string);
	}
	
	function is_utf8($string) 
	{
		return !strlen(
			preg_replace(
				  ',[\x09\x0A\x0D\x20-\x7E]'            
				. '|[\xC2-\xDF][\x80-\xBF]'             
				. '|\xE0[\xA0-\xBF][\x80-\xBF]'         
				. '|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}'  
				. '|\xED[\x80-\x9F][\x80-\xBF]'         
				. '|\xF0[\x90-\xBF][\x80-\xBF]{2}'      
				. '|[\xF1-\xF3][\x80-\xBF]{3}'          
				. '|\xF4[\x80-\x8F][\x80-\xBF]{2}'      
				. ',sS',
				'', 
				$string
			)
		);
	}
    
    function config($name = '')
    {
        $config = getvar('**config**');
        if (strlen($name)) {
            return $config[$name];
        }
        return $config;
    }
    
    function configClass($name = '')
    {
        $config = getvar('**config**');
        $obj = new stdclass;
        foreach ($config as $key => $value) {
            $obj->$key = $value;
        }
        if (strlen($name)) {
            return $config[$name];
        }
        return $obj;
    }
    
    
    function select($table, $order, $sens, $start)
    {
        $db = db();
        $limit = config('limit');
        $q = "SELECT * FROM $table ORDER BY $order $sens LIMIT $start, $limit";
        return $db->fetchArray($q);
    }
    
    function app()
    {
        $app = app::getInstance();
        return $app;
    }
    
    function action($controller, $action, $params = array())
    {
        $get = function($name){return getvar($name);};
		$set = function($name, $value){setvar($name, $value);};
        $post = function($name){return getvarpost($name);};
        $option = function($name){return getoption($name);};
        $app = app();
        
        if (count($params)) {
            foreach ($params as $key => $value) {
                setvar($key, $value);
            }
        }
        $oldpage = getvar('**page**');
        $oldaction = getvar('**action**');
        setvar('**action**', $action);
        setvar('**page**', $controller);
		ob_start();
		require_once(DIR_CONTROLLERS . $controller . '.php');
        $objName = "controller_$controller";
        $obj = new $objName;
        $noRenderer = getvar('**noRenderer**');
        if (null === $noRenderer) {
            $controller = controller::getInstance();
            viewRenderer();
            $controller->html();
            $result = ob_get_contents();
            ob_end_clean();
        }
		
        setvar('**action**', $oldaction);
        setvar('**page**', $oldpage);
		return $result;
    }
    
    function partial($name, $page = '')
    {
        if (!strlen($page) || !isset($page)) {
            $page = getvar('**page**');
		}
        $html = file_get_contents(DIR_VIEWS . 'partials/' . $page . '/' . $name . '.html');
        $result = parsephp($html);
		return $result;
    }
    
    function php($file, $ext)
    {
        $ct = @file_get_contents($file);
        if (strlen($ct)) {
            if(strstr($ct, '{{')) {
                $ct = parsephp($ct);
            }
            $hash = md5($ct);
            $newFile = DIR_FILES . $hash . '.' . $ext;
            if (!is_file($newFile)) {
                @touch($newFile);
                file_put_contents($newFile, $ct);
            }
            return URL_SITE . 'files/' . $hash . '.' . $ext;
        } else {
            return $file;
        }
    }
    
    function recupeval($php)
	{
		$get = function($name){return getvar($name);};
		$set = function($name, $value){setvar($name, $value);};
        $post = function($name){return getvarpost($name);};
        $option = function($name){return getoption($name);};
        $app = app();
        $scriptphp = DIR_CACHE . md5($php) . '.php';
		@touch($scriptphp);
		file_put_contents($scriptphp, $php);
		ob_start();
		include($scriptphp);
		$result = ob_get_contents();
		ob_end_clean();
        @unlink($scriptphp);
		return $result;
	}
	
	function parsephp($val)
	{
		if (!is_utf8($val)) {
			$val = utf8_encode($val);
		}
        $retour = _r('_("', '<?php echo __("', $val);
		$retour = _r('")_', '"); ?>', $retour);
        $retour = _r("_('", '<?php echo __("', $retour);
		$retour = _r("')_", '"); ?>', $retour);
		$retour = _r('{{=', '<?php echo ', $retour);
		$retour = _r('{{', '<?php ', $retour);
		$retour = _r('}}', '?>', $retour);
		
		$tab = explode('££', $retour);
		if (sizeof($tab) > 1) {
			for ($i = 1 ; $i < sizeof($tab) ; $i++) {
				$seg = trim($tab[$i]);
				list($chaine, $dummy) = explode('§§', $seg, 2);
				$retour = _r('££' . $chaine . '§§', '<?php echo __("' . sl($chaine) . '"); ?>', $retour);
			}
		}
		$retour = recupeval($retour);
		return $retour;
	}
    
    function makeUrl($controller, $action = 'index', $params = array(), $urlSite = true)
    {
        $url_site = (true === $urlSite) ? URL_SITE : '';
        $url = $url_site . $controller;
        if ('index' !== $action) {
            $url .= '/' . $action;
        }
        if (count($params)) {
           $url .= '/';
           foreach ($params as $key => $value) {
                $url .= $key . '/' . $value . '/';
           }
           $url = substr($url, 0, -1);
        }
        
        $url .= '.html';
        return $url;
    }
    
    function debugWS($bug)
    {
        var_dump($bug);
        exit;
    }
    
    function makeUrlRoute($routeName, $params = array(), $urlSite = true, $ext = true)
    {
        $url_site = ($urlSite) ? URL_SITE : '';
        $routeConf = getRouteByName($routeName);
        
        if (count($routeConf)) {
            $route = $routeConf['route'];
            if (!count($params)) {
                return $url_site . $route;
            }
            $routeTab = explode('/', $route);
            for ($i = 0 ; $i < count($routeTab) ; $i++) {
                if (strlen($routeConf['param' . ($i + 1)])) {
                    $route = _r($routeTab[$i], $params[$routeConf['param' . ($i + 1)]], $route);
                }
            }
            if ($ext === true) {
                $route .= '.html';
            }
            return $url_site . $route;
        }
    }
    
    function makeUrlRouteZend($routeName, $params = array(), $urlSite = true, $ext = true)
    {
        $url_site = ($urlSite) ? URL_SITE : '';
        $routeConf = getRouteByName($routeName);
        
        if (count($routeConf)) {
            $route = $routeConf['routeWZ'];
            if (!count($params)) {
                return $url_site . $route;
            }
            $routeTab = explode('/', $route);
            for ($i = 0 ; $i < count($routeTab) ; $i++) {
                if (strlen($routeConf['param' . ($i + 1)])) {
                    $route = _r($routeTab[$i], $params[$routeConf['param' . ($i + 1)]], $route);
                }
            }
            if ($ext === true) {
                $route .= '.html';
            }
            return $url_site . $route;
        }
    }
    
    function habilitation()
    {
        $user = getoption('__user__');
        $page = getvar('**page**');
        $action = getvar('**action**');
        
        if (null !== $user && $page <> 404 && $page <> 'accueil' && $page <> 'forget') {
            $db = db();
            $role = $user->role;
            if ($role == 1)
                setvar('**isAdmin**', true);
            if (1 <> $role) {
                setvar('**isAdmin**', false);
                $q = "SELECT id FROM habilitations WHERE page = '" . $page . "' && action = '" . $action . "' && role = $role";
                $res = $db->fetchArray_one($q);
                if (!count($res))
                    setvar('**page**', 'nohabilitation');
            }
        }
    }
    
    function getMicrotime()
    {
        list($usec, $sec) = explode(" ",microtime());
        return ((float)$usec + (float)$sec);
    }
	
	function display()
	{
		if (true == config('authorized')) {
            habilitation();
        }
        
        $page = getvar('**page**');
        $action = getvar('**action**');
        
        $_404 = (is_file(DIR_CONTROLLERS . $page . '.php')) ? false : true;
        if (true === $_404) {
            setvar('**page**', 404);
        }
        
        require_once(DIR_CONTROLLERS . $page . '.php');
        
        $class = 'controller_' . $page;
        $classMethods = get_class_methods($class);

        if (!in_array($action, $classMethods)) {
            go404();
        }
            
        $display = new $class;
        $noRenderer = getvar('**noRenderer**');
        if (null === $noRenderer) {
            $controller = controller::getInstance();
            viewRenderer();
            $controller->html();
        }
        return $display;
	}
	
	function getDirs($dirName)
	{
		$allDirs = array_filter(glob($dirName . '/*'), 'is_dir'); 
		foreach ($allDirs as $dir) {
			if (is_dir($dir))
				$allDirs = array_merge($allDirs, getDirs($dir));
		}
		return $allDirs;
	}
	
	function cleanDirs($dirs, $stack)
	{
		$return = array();
		foreach ($dirs as $dir) {
			if (!is_utf8($dir))
				$dir = utf8_encode($dir);
			$return[] = _r($stack, '', $dir);
		}
		
		sort($return);
		return $return;
	}
	
	function dossier_cache($fic)
	{
		$dossier = substr($fic, -3);
		if (!is_dir(DIR_CACHE . $dossier)) {
			$oldumask = umask(0);
			mkdir(DIR_CACHE . $dossier, 0777);
			umask($oldumask);
		}
		return $dossier . '/';
	}	
	
	function parseXml($xml, $attributesKey = null, $childrenKey = null, $valueKey = null)
	{
		if (!is_object($xml))
            return null;
        if($childrenKey && !is_string($childrenKey))
			$childrenKey = '@children';
		if($attributesKey && !is_string($attributesKey))
			$attributesKey = '@attributes';
		if($valueKey && !is_string($valueKey))
			$valueKey = '@values';

		$return = array();
		$name = $xml->getName();
		$_value = trim((string)$xml);
		
		if(!strlen($_value))
			$_value = null;

		if(null !== $_value) {
			if($valueKey)
				$return[$valueKey] = $_value;
			else
				$return = $_value;
		}

		$children = array();
		$first = true;
		foreach($xml->children() as $elementName => $child) {
			$value = parseXml($child, $attributesKey, $childrenKey,$valueKey);
			if(isset($children[$elementName])) {
				if(is_array($children[$elementName])) {
					if($first) {
						$temp = $children[$elementName];
						unset($children[$elementName]);
						$children[$elementName][] = $temp;
						$first = 0;
					}
					$children[$elementName][] = $value;
				} else
					$children[$elementName] = array($children[$elementName], $value);
			} else
				$children[$elementName] = $value;
		}
		if($children) {
			if($childrenKey)
				$return[$childrenKey] = $children;
			else
				$return = array_merge($return,$children);
		}

		$attributes = array();
		foreach($xml->attributes() as $name => $value)
			$attributes[$name] = trim($value);

		if($attributes) {
			if($attributesKey)
				$return[$attributesKey] = $attributes;
			else
				$return = array_merge($return, $attributes);
		}

		return $return; 
	}
    
    function error_alert() 
    {
        if(is_null($e = error_get_last()) === false) {
            $errors = getvar('**errors**');
            if (false === $errors) {
                $errors = array();
            }
            
            if (!in_array(md5(serialize($e)), $errors)) {
                extract($e);
                $errorLog = "\nType: $type\nFile: $file\nLine: $line\nError: $message";
                $errors[] = md5(serialize($e));
                setvar('**errors**', $errors);
                applog($errorLog);
            }
        } 
    }
    
    function applog($str)
    {
        $flux = @fopen(LOG_FILE, 'a', false);
        if (! $flux)
            throw new Exception('Impossible d\'ouvrir le flux');
         
        $redacteur = new Zend_Log_Writer_Stream($flux);
        $logger = new Zend_Log($redacteur);
        $logger->info($str);
    }
    
    function pagination($page_courante, $total)
	{			
		$page = getvar('**page**');
        $action = getvar('**action**');
        $limite = config('limit');
        
        $sens = getoption('sens_' . $page);
        $page_courante = getoption('numPage_' . $page);
        $order = getoption('order_' . $page);
        $start = getoption('start_' . $page);
        
        $options = array(
            'numPage_' . $page => '##numPage##',
            'order_' . $page => $order,
            'sens_' . $page => $sens,
            'start_' . $page => $start
        );
        
        $url = makeUrl($page, $action, $options);
        
        
		$html = '<span class="page_numbers" id="page_numbers">';
				
		if ($page_courante > 1)
			$html .= '<a href="' . _r('##numPage##', 1, $url) . '"><img title="Aller page 1" alt="Aller page 1" src="' . URL_SITE . 'img/first.png" style="position: relative; top: 4px;" /></a>&nbsp;&nbsp;<a href="' . _r('##numPage##', ($page_courante - 1), $url) . '"><img style="position: relative; top: 4px;" title="Aller page ' . ($page_courante - 1) . '" alt="Aller page ' . ($page_courante - 1) . '" src="' . URL_SITE . 'img/previous.png" /></a>&nbsp;&nbsp;&nbsp;';
				
		$nbpages = ceil($total / $limite);
				
		if ($page_courante < 5) {
			$submax = 5;
			if ($submax > $nbpages)
				$submax = $nbpages;
					
			for ($i = 1 ; $i <= $submax ; $i++) {
				if ($i == $page_courante)
					$html .= '<span class="page_courante"><a href="#" onclick="return false;">' . $i . '</a></span>&nbsp;';
				else
					$html .= '<a href="' . _r('##numPage##', $i, $url) . '">' . $i . '</a>&nbsp;';
			}
					
			if ($nbpages > $submax) {
				if ((($nbpages - 3) - $submax) > 1)
						$html .= '<strong>&hellip;</strong>&nbsp;';
							
				for ($i = $nbpages - 3 ; $i <= $nbpages ; $i++)
						$html .= '<a href="' . _r('##numPage##', $i, $url) . '">' . $i . '</a>&nbsp;';
			}
		} else {
            if ($page_courante < $nbpages - 5) {
				for ($i = 1 ; $i <= 3 ; $i++)
					$html .= '<a href="' . _r('##numPage##', $i, $url) . '">' . $i . '</a>&nbsp;';
						
				if ($page_courante - $i > 1)
					$html .= '<strong>&hellip;</strong>&nbsp;';
						
				for ($i = $page_courante - 1 ; $i <= $page_courante + 5 ; $i++) {
					if ($i == $page_courante)
						$html .= '<span class="page_courante"><a href="#" onclick="return false;">' . $i . '</a></span>&nbsp;';
					else
						$html .= '<a href="' . _r('##numPage##', $i, $url) . '">' . $i . '</a>&nbsp;';
				}
						
				$debmin = $nbpages - 3;
						
				if ($debmin <= $page_courante + 5)
					$debmin = $page_courante + 6;
							
				if (($debmin - $i) > 1 && $debmin <> $nbpages)
					$html .= '<strong>&hellip;</strong>&nbsp;';
							
				for ($i = $debmin ; $i <= $nbpages ; $i++)
					$html .= '<a href="' . _r('##numPage##', $i, $url) . '">' . $i . '</a>&nbsp;';
			} else {
				for ($i = 1 ; $i <= 3 ; $i++)
					$html .= '<a href="' . _r('##numPage##', $i, $url) . '">' . $i . '</a>&nbsp;';
						
					$debmin = ($page_courante - 4 <= 3) ? 4 : $page_courante - 4;
						
				if ($debmin - 3 > 1)
					$html .= '<strong>&hellip;</strong>&nbsp;';
						
				for ($i = $debmin ; $i < $page_courante ; $i++)
					$html .= '<a href="' . _r('##numPage##', $i, $url) . '">' . $i . '</a>&nbsp;';
							
				if ($page_courante - $i > 1)
					$html .= '<strong>&hellip;</strong>&nbsp;';
						
				for ($i = $page_courante ; $i <= $nbpages ; $i++) {
					if ($i == $page_courante)
							$html .= '<span class="page_courante"><a href="#" onclick="return false;">' . $i . '</a></span>&nbsp;';
					else
						$html .= '<a href="' . _r('##numPage##', $i, $url) . '">' . $i . '</a>&nbsp;';
				}
			}
		}
			
		if ($page_courante < $nbpages)
				$html .= '&nbsp;&nbsp;&nbsp;<a href="' . _r('##numPage##', ($page_courante + 1), $url) . '"><img style="position: relative; top: 4px;" title="Aller page ' . ($page_courante + 1) . '" alt="Aller page ' . ($page_courante + 1) . '" src="' . URL_SITE . 'img/next.png" /></a>&nbsp;&nbsp;<a href="' . _r('##numPage##', $nbpages, $url) . '"><img style="position: relative; top: 4px;" title="Aller page ' . ($nbpages).'" alt="Aller page ' . $nbpages . '" src="'.URL_SITE.'img/last.png" /></a>';
		$html .= '</span>';
				
		return $html;
	}
?>